package processor;

import models.Account;

import org.apache.commons.lang3.StringUtils;

import play.db.jpa.JPA;
import play.libs.F.Callback0;
import prefix.util.JPAUtil;

import service.ActorService;
import service.exception.AccountException;
import service.exception.AccountException.CODE;
import service.impl.AccountServiceImpl;

public class AccountProcessor extends AccountServiceImpl {

    public AccountProcessor(Account account) {
        super(account);
    }

    public void addNewBankAccount(ActorService actor, Account.ChineseProvince province, String city,
            Account.FinancialInstitution institution, String accountNumber) throws AccountException {
        generalValidate(actor, province, city, institution, accountNumber);
        try {
            JPAUtil.beginTransaction();
            this.getDbaccount().setValues(actor.getDBActor().getId(), actor.getDBActor().getFullName(), province, city,
                    institution, accountNumber);
            JPAUtil.em().persist(this.getDbaccount());
            JPAUtil.commitTransaction();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new AccountException(CODE.ERROR_IN_ADDBANKACCOUNT, e);
        } finally {
            JPAUtil.closeEM();
        }

    }

    public void updateCurrentBankAccount(ActorService actor, Account.ChineseProvince province, String city,
            Account.FinancialInstitution institution, String accountNumber) throws AccountException {
        try {
            generalValidate(actor, province, city, institution, accountNumber);
            JPAUtil.beginTransaction();
            this.getDbaccount().setValues(actor.getDBActor().getId(), actor.getDBActor().getFullName(), province, city,
                    institution, accountNumber);
            JPAUtil.em().merge(this.getDbaccount());
            JPAUtil.commitTransaction();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new AccountException(CODE.UNKNOWN, e);
        } finally {
            JPAUtil.closeEM();
        }
    }

    private void generalValidate(ActorService actor, Account.ChineseProvince province, String city,
            Account.FinancialInstitution institution, String accountNumber) throws AccountException {
        if (actor == null || actor.getDBActor() == null || actor.getDBActor().getId() == null)
            throw new AccountException(CODE.INVALID_ACTOR);
        if (province == null || !province.hasCity(city))
            throw new AccountException(CODE.INVALID_CITY_PROVINCE);
        if (institution == null)
            throw new AccountException(CODE.INVALID_INSTITUTION);
        if (StringUtils.isEmpty(accountNumber))
            throw new AccountException(CODE.INVALID_ACCOUNT_NUM);
    }

}